
from  helper import OcrHelper
import tornado.ioloop
import tornado.web
import aiofiles
import datetime
import uuid
import os
from exception import *
 
class MainHandler(tornado.web.RequestHandler):

    settings = {
        'MEDIA_ROOT': './temp/'
    }

    def error(self, message='error', code=-1):
        ret_data = {}
        ret_data['code'] = code
        ret_data['message'] = message
        self.finish(ret_data)

    def success(self, data = None, message='success', code=200):
        ret_data = {}
        ret_data['code'] = code
        ret_data['message'] = message
        ret_data['data'] = data
        self.finish(ret_data)

    async def post(self):
        ret_data = {}
        files_meta = self.request.files.get("file", None)
        startTime = datetime.datetime.now() # 开始时间
        ocr = OcrHelper()
        # print(files_meta)
        if not files_meta:
            self.set_status(400)
            # ret_data["message"] = "请上传图片"
            self.error('请上传文件')
        else:
            for meta in files_meta:
                try:
                    filename = meta["filename"]
                    content_type = meta["content_type"]
                    new_filename = "{uuid}_{filename}".format(uuid=uuid.uuid1(), filename=filename)
                    file_path = os.path.join(self.settings["MEDIA_ROOT"], new_filename)

                    async with aiofiles.open(file_path, "wb") as f:
                        await f.write(meta["body"])
                        
                    ret_data = ocr.handle(file_path)
                except Exception as e:
                    self.error(e)
        
        os.remove(file_path)
        endTime = datetime.datetime.now() # 结束时间
        ret_data['cost_seconds'] = (endTime - startTime).seconds

        self.success(ret_data)

application = tornado.web.Application([(r"/ocr", MainHandler), ])

if __name__ == "__main__":
    application.listen(8868)
    tornado.ioloop.IOLoop.instance().start()